package com.bub.pay.core.manager.user.async;

import com.bub.pay.core.dao.SysLoginLogDao;
import com.bub.pay.core.dao.SysUserDao;
import com.bub.pay.core.manager.system.CurrentSystemManager;
import com.bub.pay.core.enums.SysLoginTypeEnum;
import com.bub.pay.core.entity.domain.SysLoginLog;
import com.bub.pay.core.entity.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class AsyncLogoutLogRunnable implements Runnable {

    /**
     * Logger
     */
    private static final Logger log = LoggerFactory.getLogger(AsyncLogoutLogRunnable.class);

    private final Long userId;
    private final SysUserDao sysUserDao;
    private final SysLoginLogDao sysLoginLogDao;
    private final CurrentSystemManager currentSystemManager;
    private Date logoutTime;
    private String reqIp;

    public AsyncLogoutLogRunnable(Long userId, SysUserDao sysUserDao, SysLoginLogDao sysLoginLogDao, CurrentSystemManager currentSystemManager, String reqIp) {
        this.userId = userId;
        this.sysUserDao = sysUserDao;
        this.sysLoginLogDao = sysLoginLogDao;
        this.currentSystemManager = currentSystemManager;
        this.logoutTime = new Date();
        this.reqIp = reqIp;
    }

    private boolean isEmptyParam() {
        return null == sysUserDao || null == sysUserDao || null == sysLoginLogDao;
    }

    @Override
    public void run() {
        if (isEmptyParam()) {
            log.error("AsyncLogoutLogRunnable parameter must not be null");
            return;
        }
        SysUser sysUser = sysUserDao.selectByPrimaryKey(userId);
        if(sysUser == null){
            log.error("AsyncLogoutLogRunnable sysUser must not be null");
            return;
        }
        SysLoginLog sysLoginLog = new SysLoginLog();
        sysLoginLog.setCreateId(sysUser.getId());
        sysLoginLog.setCreateName(sysUser.getUserName());
        sysLoginLog.setCreateDate(logoutTime);
        sysLoginLog.setUserType(sysUser.getUserType());
        sysLoginLog.setIp(reqIp);
        sysLoginLog.setDelFlag(false);
        sysLoginLog.setType(SysLoginTypeEnum.logout.getType());
        sysLoginLog.setSystemId(currentSystemManager.getModule().getSn());
        sysLoginLog.setSystemName(currentSystemManager.getModule().getDesc());
        sysLoginLogDao.insert(sysLoginLog);
    }

}
